package calvin.study.rabbitmq.simple.simple;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;

public class Consumer {

	public static void main(String[] args) {
		// 创建连接工厂
		ConnectionFactory connectionFactory = new ConnectionFactory();
		connectionFactory.setHost("10.4.8.128");
		connectionFactory.setPort(5672);
		connectionFactory.setVirtualHost("test");

		Connection conn = null;
		Channel channel = null;
		try {
			// 创建连接
			conn = connectionFactory.newConnection("生产者");
			// 通过连接获取通道
			channel = conn.createChannel();

			// 消费者接收消息
			channel.basicConsume("simple_queuq1", true, new DeliverCallback() {
				@Override
				public void handle(String consumerTag, Delivery message) throws IOException {
					System.out.println("收到的消息是：" + new String(message.getBody(), "UTF-8"));
				}
			}, new CancelCallback() {// 接收失败回调函数
				@Override
				public void handle(String consumerTag) throws IOException {
					System.out.println("消息接收失败");
				}
			});

		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			try {
				channel.close();
				conn.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (TimeoutException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
